package com.distribute.application.api.utils;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.distribute.framework.core.web.helper.Utils;
import com.distribute.framework.plugin.Cache;


public class WeiXinAccessTokenUtil {
	private static final Logger log = LoggerFactory
			.getLogger(WeiXinAccessTokenUtil.class);


	/**
	 * 
	 * 获取微信access_token <功能详细描述>
	 * 
	 * @param appid
	 * @param secret
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	public String getWeChatAccessTokens() {
		String accessToken = Cache.getValue("distributeAccessToken");

		if (Utils.empty(accessToken)) {
			StringBuilder requestUrl = new StringBuilder();
			requestUrl
					.append("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=")
					.append(Utils.config("wx.mp1.appid")).append("&secret=")
					.append(Utils.config("wx.mp1.secret"));
			CloseableHttpClient client = HttpClients.createDefault();
			HttpGet httpGet = new HttpGet(requestUrl.toString());
			CloseableHttpResponse response = null;
			try {
				response = client.execute(httpGet);
				HttpEntity entity = response.getEntity();
				// {"access_token":"ACCESS_TOKEN","expires_in":7200}
				AccessToken at = JSONObject.parseObject(
						EntityUtils.toString(entity), AccessToken.class);
				log.info("微信公众号返回的access_token:" + at.getAccess_token());
				// 存储Redis
				Cache.setValue(WeiXinAccessTokenUtil.class, "distributeAccessToken", at.getAccess_token(), (at.getExpires_in() - 30));
				// 获取Redis
				accessToken = at.getAccess_token();
			} catch (ClientProtocolException ce) {
				log.equals(ce.getMessage());
				ce.getStackTrace();
			} catch (IOException ioe) {
				log.equals(ioe.getMessage());
				ioe.printStackTrace();
			} finally {
				if (response != null) {
					try {
						response.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			return accessToken;
		} else {
			return accessToken;
		}
	}
}
